﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace CPPEI.Coolzon.UI.XProperty.Converters
{
    /// <summary>
    /// 画刷转换器
    /// 将 
    /// <ImageSourceArray>
    ///     <ImageSource Url="..\\mn.png"/>
    ///     <ImageSource Url="..\\mn.png"/>
    /// </ImageSourceArray>
    ///  这种配置转换成画刷
    /// </summary>
    public class XImageSourceFileArrayConverter : IPropertyValueConverter
    {
        public object Convert(ConvertContext context, Metadata.ValueNode valueNode)
        {
            List<ImageSourceFile> images = new List<ImageSourceFile>();
            if(valueNode.ValueNodes == null || valueNode.ValueNodes.Count == 0)
            {
                return null;
            }
            for (int index = 0; index < valueNode.ValueNodes.Count; index++)
            {
                Metadata.ValueNode childNode = valueNode.ValueNodes[index];
                string path = childNode.Attributes["Url"].Replace("/", "\\").Replace(".\\", context.SolutionDirectory);
                BitmapImage bitmapImage = UI.SolutionResourceManager.GetImage(path);
                if (bitmapImage != null)
                {
                    images.Add(new ImageSourceFile(bitmapImage, path));
                }
            }
            return images.ToArray();
        }

        public Metadata.ValueNode ConvertBack(ConvertContext context, object value)
        {
            ImageSourceFile[] iamges = (ImageSourceFile[])value;
            if (iamges == null)
            {
                return null;
            }

            Metadata.ValueNode rootNode = new Metadata.ValueNode("ImageSourceArray");
            rootNode.Attributes = new Dictionary<string, string>();
            rootNode.ValueNodes = new List<Metadata.ValueNode>();

            XImageSourceFileConverter xConverter = new XImageSourceFileConverter();
            for (int index = 0; index < iamges.Length; index++)
            {
                rootNode.ValueNodes.Add(xConverter.ConvertBack(context, iamges[index]));
            }

            return rootNode;
        }
    }
}
